package com.supreme.cacheserver.config;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.supreme.cacheserver.config.condition.CacheConfigCondition;
import com.supreme.cacheserver.config.props.CaffeineProps;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@EnableCaching
@Configuration
@Conditional(value = CacheConfigCondition.class)
public class CaffeineCacheConfig {

    @Resource
    private CaffeineProps caffeineProps;

    @Bean
    public CacheManager caffeineCacheManager() {
        CaffeineCacheManager caffeineCacheManager = new CaffeineCacheManager();

        Caffeine<Object, Object> caffeine = Caffeine.newBuilder()
                .initialCapacity(caffeineProps.getCapacity())
                .maximumSize(caffeineProps.getMaxSize())
                .expireAfterWrite(caffeineProps.getExpireDuration(), TimeUnit.MINUTES);
        caffeineCacheManager.setCaffeine(caffeine);

        return caffeineCacheManager;
    }
}
